package groups.geographics.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import groups.geographics.Country;

public class JDBCCountryDao implements ICountryDao{

	private Connection con;

	public void create(Country country){
		try{
			int idCountry;
			ResultSet result;
			Statement stmt = con.createStatement();
			result = stmt.executeQuery("SELECT MAX(IDCOUNTRY) AS IDCOUNTRY FROM APP.COUNTRY");
			System.out.println(result.getCursorName());
			result.next();//Cursor na posicao da primeira tupla
			idCountry = result.getInt("IDCOUNTRY") + 1;
			stmt.executeUpdate("INSERT INTO APP.COUNTRY VALUES (" +
					idCountry + ", '" + country.getName() + "' , '" + country.getContinent() + "')");
		}
		catch(SQLException e){
			e.printStackTrace();
		}

	}	
	
	public JDBCCountryDao(Connection con){
		try {
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.con = con;
	}

	public void deleteExact(Country country) {		
		try {
			Statement stmt = con.createStatement();
			stmt.executeUpdate("DELETE FROM APP.COUNTRY WHERE IDCOUNTRY = " + country.getIdCountry());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void deleteAny(Country country){
		
	}

	public Country read(Country country) {
		try {
			ResultSet result;
			Statement stmt = con.createStatement();
			result = stmt.executeQuery("SELECT * FROM APP.COUNTRY WHERE IDCOUNTRY = " + country.getIdCountry());
			result.next();
			country.setName(result.getString("NAME"));
			country.setContinent(result.getString("CONTINENT"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return country;
	}

	public Vector<Country> readAll() {
		Vector<Country> countryVector = new Vector<Country>();
		try {
			ResultSet result;
			Statement stmt = con.createStatement();
			result = stmt.executeQuery("SELECT * FROM APP.COUNTRY");
					while (result.next()){
						Country country = new Country();
						country.setIdCountry(result.getInt("IDCOUNTRY"));
						country.setName(result.getString("NAME"));
						country.setContinent(result.getString("CONTINENT"));
						countryVector.add(country);
					}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return countryVector;

	}

	public void update(Country country) {
		try {
			Statement stmt = con.createStatement();
			stmt.executeUpdate("UPDATE APP.COUNTRY " +
					"SET NAME='"+ country.getName() + "', CONTINENT='" + country.getContinent() + "' WHERE IDCOUNTRY=" + country.getIdCountry());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Country searchExact(Country country) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Country searchAny(Country country) {
		// TODO Auto-generated method stub
		return null;
	}

}
